/**
 * 
 */
package com.jeecms.wicool.dao.shops.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

import com.jeecms.cms.entity.main.CmsUser;
import com.jeecms.common.hibernate3.Finder;
import com.jeecms.common.hibernate3.HibernateBaseDao;
import com.jeecms.common.page.Pagination;
import com.jeecms.wicool.dao.shops.RedPacketDao;
import com.jeecms.wicool.entity.shops.RedPacket;

/**
 * @author spring
 *
 */
@Repository
public class RedPacketDaoImpl extends HibernateBaseDao<RedPacket, Integer>
		implements RedPacketDao {

	@Override
	public Pagination getPage(String name,String startDate,String endDate, int pageNo, int pageSize,
			CmsUser user) {
		Finder f = Finder.create("from RedPacket bean where 1=1 ");
		if (!StringUtils.isBlank(name)) {
			f.append(" and bean.name = :name");
			f.setParam("name", name);
		}
		if(user.getShopId()!=null){
			f.append(" and bean.shop.id = :shopId");
			f.setParam("shopId",user.getShopId());
		}
		SimpleDateFormat simpleTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if(!StringUtils.isBlank(startDate)){
			startDate += " 00:00:00";
			try {
				Date start = simpleTime.parse(startDate);
				f.append(" and bean.startTime >= :start");
				f.setParam("start",  start );
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		if(!StringUtils.isBlank(endDate)){
			endDate += " 00:00:00";
			try {
				Date end = simpleTime.parse(endDate);
				f.append(" and bean.endTime <= :end");
				f.setParam("end",  end );
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		f.append(" order by bean.endTime desc");
		return find(f, pageNo, pageSize);
	}

	@Override
	public RedPacket findById(Integer id) {
		return get(id);
	}


	@Override
	public RedPacket save(RedPacket bean) {
		getSession().save(bean);
		return bean;
	}

	@Override
	public RedPacket deleteById(Integer id) {
		RedPacket obj = get(id);
		if(obj != null){
			getSession().delete(obj);
		}
		return obj;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<RedPacket> getAll(CmsUser user) {
		Finder f = Finder
				.create("select bean from RedPacket bean where 1 = 1 ");
		if(user.getShopId()!=null){
			f.append(" and bean.shop.id = :shopId");
			f.setParam("shopId",user.getShopId());
		}
		f.append(" order by bean.startTime desc");
		return find(f);
	}

	@Override
	protected Class<RedPacket> getEntityClass() {
		return RedPacket.class;
	}

}
